/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

'use strict';

(function () {
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // TODO1: Determine if the user's version of Office supports all the 
            //        Office.js APIs that are used in the tutorial.
            if (!Office.context.requirements.isSetSupported('ExcelApi', 1.7)) {
                console.log('Sorry. The tutorial add-in uses Excel.js APIs that are not available in your version of Office.');
            }

            // TODO2: Assign event handlers and other initializaton logic.
            $('#create-table').click(getHPO);
            $('#hpo_tree').on('select_node.jstree', function (e, data) {
                getHPO(data.node.text);
            });

        });
    };

    // TODO3: Add handlers and business logic functions here.
    function getHPOText(hpo_text, text_type){
        if(text_type == 'id'){
            return hpo_text.substring(0, 10)
        }
        if(text_type == 'name') {
            return hpo_text.substring(11)
        }
        else return  hpo_text.substring(0, 10) + "(" + hpo_text.substring(11) + ")"
    }
    function getHPO(text) {
        Excel.run(function (context) {
            const currentWorksheet = context.workbook.worksheets.getActiveWorksheet;
            const currentCell = context.workbook.getActiveCell();
            currentCell.load('values');
            return context.sync().then(function () {
                console.log('current values: ' + currentCell.values);
                if (
                    currentCell.values == ''
                ) {
                    currentCell.values = text;
                }
                else {
                    currentCell.values = currentCell.values + '\n' + text;
                }
            });
        })
            .catch(function (error) {
                console.log("Error: " + error);
                if (error instanceof OfficeExtension.Error) {
                    console.log("Debug info: " + JSON.stringify(error.debugInfo));
                }
            });
    }
})();